package luke4fun.wheresmymoney.fragments;

import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import luke4fun.wheresmymoney.DoAccActivity;
import luke4fun.wheresmymoney.R;
import luke4fun.wheresmymoney.SearchableActivity;
import luke4fun.wheresmymoney.adapter.list.impl.DayAccAdapter;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;
import luke4fun.wheresmymoney.panel.TrendChartPanel;
import luke4fun.wheresmymoney.service.async.HomeAsyncTask;
import luke4fun.wheresmymoney.util.DateUtil;
import luke4fun.wheresmymoney.util.FormatUtil;

public class HomeFragment extends Fragment {

	private View layout;
	private TextView monthTV;
	private TextView monthExpenseTV;
	private ListView expenseList;
    private TrendChartPanel trendPanel;
	
	private AccDBHelper dbHelper;
	private DayAccAdapter adapter;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout = inflater.inflate(R.layout.fragment_home, container, false);
		
		initView();
		setView();
		
		setHasOptionsMenu(true);
		return layout;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		dbHelper = new AccDBHelper(getActivity());
	}
	
	@Override
	public void onStart() {
		super.onStart();
		setSum();
		setList();
	}

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(getString(R.string.title_home));
        setTrend();
    }

	@Override
	public void onPause() {
		super.onPause();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_search, menu);
		inflater.inflate(R.menu.menu_add, menu);
		
		// Get the SearchView and set the searchable configuration
	    SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
	    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
	    // Assumes current activity is the searchable activity
	    searchView.setSearchableInfo(searchManager.getSearchableInfo(
            new ComponentName(getActivity(), SearchableActivity.class)
        ));
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_add_new:
				Intent intent = new Intent(getActivity(), DoAccActivity.class);
				startActivity(intent);
				break;
			case R.id.menu_search:
				getActivity().onSearchRequested();
				break;
		}
		return true;
	}
	
	private void initView() {
		monthTV = (TextView) layout.findViewById(R.id.month);
		monthExpenseTV = (TextView) layout.findViewById(R.id.month_expense);
		expenseList = (ListView) layout.findViewById(R.id.expense_list);
		adapter = new DayAccAdapter(getActivity());
		expenseList.setAdapter(adapter);
        trendPanel = (TrendChartPanel) layout.findViewById(R.id.trendPanel);
	}
	
	private void setView() {
		Calendar c = Calendar.getInstance();
		monthTV.setText(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()));
	}
	
	private void setSum() {
        long millis = DateUtil.getCurrentMonthInMillis();
        String[] args = new String[] { millis + "", DateUtil.getNextMonthInMillis(millis) + "" };
        SQLiteDatabase db = dbHelper.getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT SUM(price) as price FROM " + DBConstants.V_RECORD + " WHERE dataTime >= ? AND dataTime < ? AND pid = -1", args);
		
		while (cursor.moveToNext()) {
			monthExpenseTV.setText(""
                    + FormatUtil.formatNumber(cursor.getInt(cursor.getColumnIndex(DBConstants.RECORD_PRICE))));
		}
		
		cursor.close();
	}

    private void setTrend() {
        long millis = DateUtil.getCurrentMonthInMillis();
        String[] args = new String[] { millis + "", DateUtil.getNextMonthInMillis(millis) + "" };
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        List<Long> expenseList = new ArrayList<Long>();
        Cursor cursor = db.rawQuery("SELECT SUM(price) as price FROM " + DBConstants.V_RECORD +
                " WHERE dataTime >= ? AND dataTime < ? AND pid = -1 GROUP BY dataTime ORDER BY dataTime ASC", args);
        while(cursor.moveToNext()) {
            expenseList.add(cursor.getLong(cursor.getColumnIndex(DBConstants.RECORD_PRICE)));
        }

        trendPanel.invalidate();
        trendPanel.setDataList(expenseList);
//        trendPanel.setUpAnimationPath();
//        trendPanel.startDrawPath();
    }
	
	private void setList() {
		new HomeAsyncTask(getActivity(), adapter, DateUtil.getTodayInMillis()).execute();
	}
}
